//
//  ComposeViewController.swift
//  WBDemo
//
//  Created by Jin on 2018/5/11.
//  Copyright © 2018年 com.baidu.123. All rights reserved.
//

import UIKit
import SnapKit

class ComposeViewController: UIViewController {

    @IBOutlet weak var composeTextView:ComposeTextView!
    @IBOutlet weak var picPickerCollectionView:PicPickerCollectionView!
    
    @IBOutlet weak var toolBarBottomCons: NSLayoutConstraint!
    @IBOutlet weak var picPickerHCons: NSLayoutConstraint!
    
    private var isPickerDismiss:Bool = false
    
    private lazy var composeTitleView : ComposeTitleView = {
        let titleView = ComposeTitleView(frame: CGRect(x: 0, y: 0, width: 200, height: 44))
        titleView.backgroundColor = UIColor.red
        return titleView
    }()
    private lazy var images:[UIImage] = [UIImage]()
    private lazy var emotionVc = EmotionViewController {[weak self] (emotion) in
        self?.composeTextView.insertEmotionToTextView(emotion: emotion)
        self?.textViewDidChange(self!.composeTextView)
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()

        setupNavigationBar()
        
        //监听通知
        NotificationCenter.default.addObserver(self, selector: #selector(keyboardWillChangeFrame(note:)), name: .UIKeyboardWillChangeFrame, object: nil)
        NotificationCenter.default.addObserver(self, selector: #selector(addPhotoBtnClick(note:)), name: NSNotification.Name(rawValue: JLPicPickerAddPhotoNote), object: nil)
        NotificationCenter.default.addObserver(self, selector: #selector(deletePhotoBtnClick(note:)), name: NSNotification.Name(rawValue: JLPicPickerDeletePhotoNote), object: nil)
    }
    
    override func viewDidAppear(_ animated: Bool) {
        super.viewDidAppear(animated)
        //判断是否是选择照片后显示
        if !isPickerDismiss {
            composeTextView.becomeFirstResponder()
        }
        isPickerDismiss = false
    }
    
    deinit {
        NotificationCenter.default.removeObserver(self)
    }
}
 
//设置UI
extension ComposeViewController {
    private func setupNavigationBar(){
        navigationItem.leftBarButtonItem = UIBarButtonItem(title: "取消", style: .plain, target: self, action: #selector(closeItemClick))
        navigationItem.rightBarButtonItem = UIBarButtonItem(title: "发送", style: .plain, target: self, action: #selector(sendItemClick))
        navigationItem.rightBarButtonItem?.isEnabled = false
    
        self.navigationItem.titleView = composeTitleView
    }
}

//事件监听
extension ComposeViewController {
    //取消发布按钮
    @objc private func closeItemClick(){
        composeTextView.resignFirstResponder()
        dismiss(animated: true, completion: nil)
    }
    //发送按钮
    @objc private func sendItemClick(){
        let statusText = composeTextView.getTextViewAttributeString()
        let access_token = (UserAccount.loadUserAccount()?.access_token)!
        NetworkTools.shareInstance.sendMessageStatus(statusText: statusText, access_token: access_token) { (isSuccess) in
            if !isSuccess {
                return
            }
            
            
        }
    }
    //监听键盘弹出
    @objc private func keyboardWillChangeFrame(note:Notification){
        
        let duration = note.userInfo![UIKeyboardAnimationDurationUserInfoKey] as! TimeInterval
        let endFrame = (note.userInfo![UIKeyboardFrameEndUserInfoKey] as! NSValue).cgRectValue
        let margin = UIScreen.main.bounds.height - endFrame.origin.y
        
        toolBarBottomCons.constant = margin
        UIView.animate(withDuration: duration, animations: {
            self.view.layoutIfNeeded()
        }) { (_) in
            
        }
    }
    //发布页面选择图片
    @IBAction func picPickerItemClick(_ sender: UIBarButtonItem) {
        composeTextView.resignFirstResponder()
        picPickerHCons.constant = UIScreen.main.bounds.height * 0.65
        UIView.animate(withDuration: 0.5) {
            self.view.layoutIfNeeded()
        }
    }
    //发布页面表情键盘
    @IBAction func emojiItemClick(_ sender: UIBarButtonItem) {
        composeTextView.resignFirstResponder()
        composeTextView.inputView = composeTextView.inputView != nil ? nil : emotionVc.view
        composeTextView.becomeFirstResponder()
    }
    
    //添加照片
    @objc private func addPhotoBtnClick(note:Notification){
        if !UIImagePickerController.isSourceTypeAvailable(.photoLibrary) {
            return
        }
        let ipc = UIImagePickerController()
        ipc.sourceType = .photoLibrary
        ipc.delegate = self
        present(ipc, animated: true, completion: nil)
    }
    //删除照片
    @objc private func deletePhotoBtnClick(note:Notification){
        let deleteImage = note.object as! UIImage
        images.remove(at: images.index(of: deleteImage)!)
        picPickerCollectionView.images = images
    }

}

//代理方法
extension ComposeViewController: UITextViewDelegate{
    func textViewDidChange(_ textView: UITextView) {
        self.composeTextView.placeholderLabel.isHidden = textView.hasText
        navigationItem.rightBarButtonItem?.isEnabled = textView.hasText
    }
    
    func scrollViewDidScroll(_ scrollView: UIScrollView) {
        composeTextView.resignFirstResponder()
    }
}

extension ComposeViewController: UIImagePickerControllerDelegate,UINavigationControllerDelegate {
    func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : Any]) {
        let image = info[UIImagePickerControllerOriginalImage] as! UIImage
        images.append(image)
        picPickerCollectionView.images = images
        picker.dismiss(animated: true,completion: nil)
        isPickerDismiss = true
    }
}
